package com.activity;

import com.misc.Tool;
import com.type.ByteArrayParcelable;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

public class RegisterActivity extends Activity {
	// constant
	final int REGISTER_INTERACT = 101;
	static final String REGISTER_SUCCESS_PH_NUM = "register_success_ph_num";
	static final String REGISTER_SUCCESS_NAME = "register_success_name";
	static final String REGISTER_SUCCESS_AVATAR = "register_success_avatar";
	
	// field
	EditText etPhNum, etPassword, etUserName;
	Button btnAvatar, btnFinishRegister;
	
	Boolean  isPhNumFilled = false,  isPasswordFilled = false,  isUserNameFilled = false;
	String  phNum,  name;
	Bitmap avatar;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_activity);
		avatar = ((BitmapDrawable) getResources().getDrawable(R.drawable.default_avatar)).getBitmap();
		
		etPhNum = (EditText) findViewById(R.id.etPhoneNumber);
		etPassword = (EditText) findViewById(R.id.etPassword);
		etUserName = (EditText) findViewById(R.id.etUserName);
		btnFinishRegister = (Button) findViewById(R.id.btnFinishRegister);
		
		etPhNum.addTextChangedListener(new TextWatcher() {
	        public void onTextChanged(CharSequence s, int start, int before, int count) {
	        	isPhNumFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhNumFilled && isPasswordFilled && isUserNameFilled);
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	        }
	        public void afterTextChanged(Editable s) {
	        }
	    });
		etPassword.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				isPasswordFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhNumFilled && isPasswordFilled && isUserNameFilled);
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void afterTextChanged(Editable s) {
			}
		});
		etUserName.addTextChangedListener(new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				isUserNameFilled = !TextUtils.isEmpty(s);
				btnFinishRegister.setEnabled(isPhNumFilled && isPasswordFilled && isUserNameFilled);
			}
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			public void afterTextChanged(Editable s) {
			}
		});
		
		btnAvatar = (Button) findViewById(R.id.btnAvatar);
		btnAvatar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				intent.putExtra("return-data", true);
				startActivityForResult(intent, 0);
			}
		});
		
		btnFinishRegister.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				phNum = etPhNum.getText().toString();
				name = etUserName.getText().toString();
				(new RegisterTask(RegisterActivity.this)).execute(new ParamForRegisterTask(
																		MainActivity.SERVER_IP, 
																		Integer.parseInt(MainActivity.PORT), 
																		phNum, 
																		etPassword.getText().toString(), 
																		name, 
																		Tool.bitmap2ByteArray(avatar)));
			}
		});
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0 && intent != null) {
			avatar = intent.getParcelableExtra("data");
			Matrix matrix = new Matrix();
			matrix.postScale(150 / (float) avatar.getWidth(), 130 / (float) avatar.getHeight());
			btnAvatar.setBackgroundDrawable(new BitmapDrawable(Bitmap.createBitmap(avatar, 0, 0, avatar.getWidth(), avatar.getHeight(), matrix, true)));
			btnAvatar.setHint("");
		}
	}
	
	
	class ParamForRegisterTask {
		String serverIp;
		int port;
		String phNum;
		String password;
		String name;
		byte[] avatar;
		public ParamForRegisterTask(String serverIp, int port, String phNum, String password, String name, byte[] avatar) {
			super();
			this.serverIp = serverIp;
			this.port = port;
			this.phNum = phNum;
			this.password = password;
			this.name = name;
			this.avatar = avatar;
		}
		public String getServerIp() {
			return serverIp;
		}
		public int getPort() {
			return port;
		}
		public String getPhNum() {
			return phNum;
		}
		public String getPassword() {
			return password;
		}
		public String getName() {
			return name;
		}
		public byte[] getAvatar() {
			return avatar;
		}
	}
	class RegisterTask extends AsyncTask<ParamForRegisterTask, Void, Void> {
	    RegisterActivity registerActivity;
	    String exceptionInfo = null;
	
	    public RegisterTask(RegisterActivity registerActivity) {
	        this.registerActivity = registerActivity;
	    }
	
	    @Override
		protected Void doInBackground(ParamForRegisterTask... params) {
	    	Socket socket = null;
	    	DataOutputStream dos = null;	
	    	DataInputStream dis = null;
			try {
				socket = new Socket(params[0].getServerIp(), params[0].getPort());
				dos = new DataOutputStream(socket.getOutputStream());
				dis = new DataInputStream(socket.getInputStream());
				dos.writeInt(REGISTER_INTERACT);
				
				dos.writeUTF(params[0].getPhNum());
				if(dis.readBoolean()) {
					dos.writeUTF(params[0].getPassword());
					dos.writeUTF(params[0].getName());
					Tool.sendByteArray(dos, params[0].getAvatar());
				} else
					exceptionInfo = "this phone number is already registered, please choose another number";
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					dis.close();
					dos.close();
					socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}
	
	    @Override
	    protected void onPostExecute(Void result) {
	        if (registerActivity != null) {
	            registerActivity.onRegisterTaskComplete(exceptionInfo);
	        }
	    }
	}
	
	
	public void onRegisterTaskComplete(String exceptionInfo) {
		if(exceptionInfo==null) {
			Intent intent = new Intent();
			intent.putExtra(REGISTER_SUCCESS_PH_NUM, phNum);
			intent.putExtra(REGISTER_SUCCESS_NAME, name);
			intent.putExtra(REGISTER_SUCCESS_AVATAR, new ByteArrayParcelable(Tool.bitmap2ByteArray(avatar)));
			setResult(RESULT_OK, intent);
			finish();
		} else
			Toast.makeText(this, exceptionInfo, Toast.LENGTH_LONG).show();
	}
}
